package com.cskaoyan.demo2.servlet;

import com.cskaoyan.demo2.bean.MarketAdmin;
import com.cskaoyan.demo2.service.AdminService;
import com.cskaoyan.demo2.util.JsonUtil;
import com.cskaoyan.demo2.util.MybatisUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/8 18:50
 */

@WebServlet("/admin/auth/*")
public class AdminAuthServlet extends CommonServlet {
    AdminService adminService = new AdminService();
    String sessionId;

    public void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 获取请求体中的jsonStr
        String jsonStr = req.getReader().readLine();
        // 将jsonStr变为对象
        MarketAdmin user = JsonUtil.read(jsonStr, MarketAdmin.class);
        // 获取输入的username 和 password
        String username = user.getUsername();
        String password = user.getPassword();

        // 设置响应的字符
        resp.setContentType("application/json;charset=utf-8");
        // 利用获取的用户名和密码到数据库中进行查询
        MarketAdmin marketAdmin = adminService.selectByUserNameAndPassword(username, password);
        if (marketAdmin != null) {
            // 如果都正确，登录成功，分配SESSIONID
            HttpSession session = req.getSession();
            // session.setAttribute("username",username);
            // session.setAttribute("password",password);
            session.setAttribute("user",marketAdmin);
            //  并返回对应的JSON字符串
            String sessionId = session.getId();
            // System.out.println(sessionId);
            resp.getWriter().println(sessionId);

            // 登录成功的提示
            resp.getWriter().println("登录成功！");

        } else {
            // 登录错误，弹出提示
            resp.getWriter().println("用户名或密码错误，请重新输入!");

        }


    }

    public void info(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        // String username = (String) session.getAttribute("username");
        // String password = (String) session.getAttribute("password");

        // 获取用户信息
        MarketAdmin user = (MarketAdmin) session.getAttribute("user");
        // 后去json信息并打印
        String jsonStr = JsonUtil.write(user);
        resp.getWriter().println(jsonStr);
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println("注销成功");

    }
}
